<template>
    <div class="full-percent">
        <div class="tables" v-if="active">
            <div v-waterfall="350">
                <div v-for="item in Object.keys(table)" class="item" :style="getStyle(item)">
                    <div class="item-inner">
                        <div style="display: flex;height: 32px;align-items: center;">
                            <div style="padding-right: 10px;width: 80px;">任务名称</div>
                            <el-input v-model="etlConfig[item].taskName" class="input-auto-resize"
                                style="width: calc(100% - 80px)!important;" />
                        </div>
                        <div style="display: flex;height: 32px;align-items: center;padding-top: 5px;">
                            <div style="padding-right: 10px;width: 80px;">表输入</div>
                            <tooltip :modelValue="item" border style="width: calc(100% - 80px)!important;" />
                        </div>
                        <div style="display: flex;height: 32px;align-items: center;padding-top: 5px;">
                            <div style="padding-right: 10px;width: 80px;">表输出</div>
                            <tooltip :modelValue="table[item]" border style="width: calc(100% - 80px)!important;"
                                placeholder="配置表输出">
                                <template #suffix>
                                    <el-icon class="el-input__icon" @click="setTableColumn(item)">
                                        <component :is="getIcon('DArrowRight')" />
                                    </el-icon>
                                </template>
                            </tooltip>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <el-drawer :show-close="false" size="100%" v-model="showDrawer" direction="rtl" destroy-on-close
            class="table-mapping-drawer forbid-select" @open="open" @closed="close" append-to-body
            :close-on-click-modal="false">
            <template #header>
                <div style="width: 60%;" v-if="active">
                    <span>从</span><span>{{ currentTable }}</span><span>到</span><span>{{
                        config.writer.tableMapping[currentTable] }}</span><span>映射</span>
                </div>
                <div style="width: 40%;text-align: right;">
                    <el-button class="font-auto-resize" @click="showDrawer = false">取消</el-button>
                    <el-button class="font-auto-resize" type="primary" @click="save">保存</el-button>
                </div>
            </template>
            <div class="mapping">
                <table-mapping ref="tableMappingRef" />
            </div>
            <div class="sql">
                <div style="height: 100%;width: 50%;">
                    <el-divider content-position="left">前置SQL</el-divider>
                    <div style="height: calc(100% - 50px);">
                        <aceEditor v-model="etlConfig[currentTable].front.sql" :options="{ lang: 'sql' }"
                            class="sql-editor" />
                    </div>
                </div>
                <div style="height: 100%;width: 50%;">
                    <el-divider content-position="left">后置SQL</el-divider>
                    <div style="height: calc(100% - 50px);">
                        <aceEditor v-model="etlConfig[currentTable].rear.sql" :options="{ lang: 'sql' }"
                            class="sql-editor" />
                    </div>
                </div>
            </div>
        </el-drawer>
    </div>
</template>

<script setup>
import { getIcon } from "@/utils/tools"
import { useRequest, useElLoading, useModalSize } from "@usehook"

const props = defineProps({
    config: {
        type: Object,
        required: true,
        default: {}
    },
    active: {
        type: Boolean,
        required: false,
        default: false
    },
    db: {
        type: Object,
        required: false,
        default: {}
    },
    etlConfig: {
        type: Object,
        required: true,
        default: {}
    }
})

let mappingConfig = $ref({})
const emit = defineEmits(['change'])
let showDrawer = $ref(false)
let currentTable = $ref("")
const tableMappingRef = ref(null)

const setTableColumn = (table) => {
    currentTable = table
    showDrawer = true
}

watch(() => props.active, active => {
    if (active) getTableColumn()
})

const tableColumn = $ref({})

const table = $computed(() => props.config.writer.tableMapping || {})

const open = () => {
    useModalSize()
    tableMappingRef.value.fill(props.etlConfig[currentTable])
    tableMappingRef.value.fillDbInfo(props.db, [])
}

const getStyle = (item) => {
    const inColumn = props.etlConfig[item]?.in?.column?.split(";") || []
    const outClumn = props.etlConfig[item]?.out?.column?.split(";") || []
    return `width: 100%;box-shadow: 0 0 0 1px ${inColumn.length === outClumn.length ? 'rgba(0, 0, 0, 0.1)' : '#bf0d0d73'} inset;`
}

const save = () => {
    tableMappingRef.value.validate().then(result => {
        if (result) {
            props.etlConfig[currentTable] = { ...props.etlConfig[currentTable], ...tableMappingRef.value.save() }
            showDrawer = false
        }
    })
}

const getTableColumn = () => {
    const tables = Array.from(new Set([...props.config.reader.selectTable.map(e => e + "." + props.config.reader.dbSequence), ...Object.values(props.config.writer.tableMapping).map(e => e + "." + props.config.writer.dbSequence)])).filter(table => !tableColumn[table])
    if (!tables.length) return
    const loading = useElLoading({ text: "正在查询表字段信息, 请稍后", target: ".console-page" })
    let getIndex = 0
    for (let table of tables) {
        if (tableColumn[table]) continue
        const sp = table.split(".")
        useRequest("/data/table/getTableColumn", { dbSequence: sp[2], tableSchema: sp[0], table: sp[1] }).then(resp => {
            if (resp && resp.status) tableColumn[table] = resp.data
        }).finally(() => {
            getIndex += 1
            if (getIndex === tables.length) setTimeout(() => {
                loading.close()
            }, 1000)
        })
    }
}

watch(() => tableColumn, () => {
    for (let key of Object.keys(mappingConfig)) {
        const tKey = key + "." + props.config.reader.dbSequence
        mappingConfig[key].allReaderColumn = tableColumn[tKey]
        mappingConfig[key].readerColumn = tableColumn[tKey]?.map(e => e.name)

        const wKey = table[key] + "." + props.config.writer.dbSequence
        mappingConfig[key].allWriterColumn = tableColumn[wKey]
        mappingConfig[key].writerColumn = tableColumn[wKey]?.map(e => e.name)
    }
}, { deep: true })

const close = () => {
    useModalSize(false)
}

watch(() => table, t => {
    mappingConfig = Object.keys(t).reduce((acc, key) => {
        let orig = mappingConfig[key] || {}
        if (!orig.name) orig.name = key
        acc[key] = orig
        return acc;
    }, {})
}, { immediate: true, deep: true })


watch(() => mappingConfig, (config) => {
    emit("change", config)
}, { deep: true })

</script>

<style>
.table-mapping-drawer .el-tag__content {
    width: 100%
}

.table-mapping-drawer .e-tooltip .disabled-style {
    color: black;
}

.table-mapping-drawer .el-drawer__body {
    height: 100%;
}

.sql-editor {
    box-shadow: 0 0 0 1px rgb(0 0 0 / 10%) inset;
    border-radius: 3px;
}

.table-mapping-drawer .el-drawer__header {
    padding-bottom: 0;
}

.table-mapping-drawer .mapping {
    height: 60%;
}

.table-mapping-drawer .sql {
    height: 40%;
    display: flex;
    gap: 30px;
}
</style>